/**
 * All rights reserved by www.xmerge.cn
 */
package net.xfok.info.cnbeta;

import java.util.ArrayList;
import java.util.Date;

import net.xfok.rss.parser.Feed;
import net.xfok.rss.parser.Rss;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

/**
 * @author YangHua
 *
 */
public class InfoService extends Service{
	private static String TAG="InfoService";
	private NotificationManager mNM;
	private SharedPreferences sp;
	private boolean notify;
	private int refresh;
	private int delete;
	private InfoItem notifyInfo;
	private String today;

	@Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    public void onStart(Intent intent,int startId){
    	super.onStart(intent, startId);
    	Log.i(TAG, "onStart");
    	mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        sp=PreferenceManager.getDefaultSharedPreferences(this);
        notify=sp.getBoolean(InfoSettings.NOTIFY_KEY, true);
        refresh=Integer.parseInt(sp.getString(InfoSettings.REFRESH_KEY, InfoSettings.DEFAULT_VALUE));
        delete=Integer.parseInt(sp.getString(InfoSettings.DELETE_KEY, InfoSettings.DEFAULT_VALUE));
        today=InfoConstant.dateToStr(new Date());
    	try{
    		if(refresh==1){
    			importInfo();
    		}else{
    			Log.i(TAG,"Manual Refresh!");
    		}
    		if(delete>0){
    			deleteInfo();
    		}else{
    			Log.i(TAG,"Manual Delete!");
    		}
    		InfoManage.delInfoItem(InfoConstant.getNextDay(today,-60), this);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    private void importInfo(){
    	if(InfoManage.checkNet(this)){
    		Rss rss=new Rss(InfoConstant.RSS_URL);
    		for(Feed feed:rss.getFeeds()){
    			InfoItem info=new InfoItem(feed);
    			info.setInfoId(String.valueOf(System.currentTimeMillis()));
    			info.setPubDate(InfoConstant.DATE_FORMAT.format(new Date()));
    			if(!InfoManage.infoIsExit(info,this)){  			
	    			String content=InfoConstant.genHtml(info.getLink());    			
	    			if(content!=null){	
	    				int saveResult=InfoConstant.saveHtml(info.getInfoId(), content);
	    				if(saveResult==InfoConstant.SAVE_SUC){
		    				InfoManage.addInfoItem(info, this); 
		    				if(notifyInfo==null){
		    					notifyInfo=info;
		    				}	 
	    				}else{
	    					Log.i(TAG, "Save HTML----->"+saveResult);
	    				}
	    			}
    			}else{
    				Log.i(TAG, info.getInfoId()+" is exit.");
//    				if(!InfoConstant.checkHtml(info.getInfoId())){
//    					String content=InfoConstant.genHtml(info.getLink());
//    					InfoConstant.saveHtml(info.getInfoId(), content);
//    				}
    			}
    		}
    		if(notify&&notifyInfo!=null){
				showNotification(notifyInfo);
				notifyInfo=null;
			}
    	}
    	sendBroadcast(new Intent(InfoConstant.ACTION_UPDATE_WIDGET));
    }
    
    private void deleteInfo(){
    	String date=today;  
    	switch (delete) {
		case 1:
			date=today;
			break;
		case 2:
			date=InfoConstant.getNextDay(today, -6);
			break;
		case 3:
			date=InfoConstant.getNextDay(today, -30);
			break;
		default:
			break;
		}
    	String selection=InfoItem.INFO_COLUMN_INFO_DATE+"<'"+date+"'";
    	InfoManage.updateInfo(selection, this);
    }
    
    private void showNotification(InfoItem info) {
    	Log.i(TAG, "show notification !");
        CharSequence text = info.getTitle()+" ["+info.getPubDate()+"]";
        Notification notification = new Notification(R.drawable.icon, text,System.currentTimeMillis());
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, InfoList.class), 0);
        notification.setLatestEventInfo(this, info.getTitle(),
                       text, contentIntent);
        mNM.notify(0, notification);
    }
    
    public void startManagingCursor(Cursor c) {
        synchronized (mManagedCursors) {
            mManagedCursors.add(new ManagedCursor(c));
        }
    }
    
    public final Cursor managedQuery(Uri uri,
            String[] projection,
            String selection,
            String[] selectionArgs,
            String sortOrder){
		Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
		if (c != null) {
		startManagingCursor(c);
		}
		return c;
	}
    
    private final ArrayList<ManagedCursor> mManagedCursors =
        new ArrayList<ManagedCursor>();
   
    private static final class ManagedCursor {
        ManagedCursor(Cursor cursor) {
            mCursor = cursor;
            mReleased = false;
            mUpdated = false;
        }
        private final Cursor mCursor;
        private boolean mReleased;
        private boolean mUpdated;
    }
}
